#!/usr/bin/env python
#coding:utf8

import os
import json
import fileutils
import md5

cwd = os.getcwd()
root_dir = os.path.join(cwd, "..")
res_dir = os.path.join(root_dir, "res")
#newres_dir = os.path.join(root_dir, "newres")
newres_dir = os.path.join(root_dir, "..", "res")

# 忽略文件夹
ignore_dir = "/default/"

filemd5List = "filemd5List.json"
tempmd5List = "tempmd5List.json"

# 生成md5
def gen_md5(dir):
    oldJsonObj = None
    fileMd5 = os.path.join(dir, filemd5List)
    if os.path.isfile(fileMd5):
        f = open(fileMd5, "r")
        jsonStr = f.read()
        f.close()
        oldJsonObj = json.loads(jsonStr)

    md5.genmd5(dir, os.path.join(dir, tempmd5List))

    compare_md5(oldJsonObj)
    pass

# 比较md5
def compare_md5(oldJsonObj):
    newJsonObj = None
    fileMd5 = os.path.join(res_dir, tempmd5List)
    if os.path.isfile(fileMd5):
        f = open(fileMd5, "r")
        jsonStr = f.read()
        f.close()
        newJsonObj = json.loads(jsonStr)
    if newJsonObj != None and oldJsonObj != None:

        print("JSON object parsing succeeded. Copy file")

        length = copy_newres(newJsonObj, oldJsonObj)

        print("#######################################################")
        print("File copy complete Count[%s]" % length)
        print("#######################################################")

        if length > 0:
            fileutils.copyfile(fileMd5, os.path.join(res_dir, filemd5List))

        return

    if newJsonObj != None and oldJsonObj is None:
        fileutils.copyfile(fileMd5, os.path.join(res_dir, filemd5List))
        print("#######################################################")
        print("%s Cpoy Success. Please Restart" % filemd5List)
        print("#######################################################")
        return
        
    print("#######################################################")
    print("JSON object parsing error")
    print("#######################################################")
    pass

def copy_newres(newDic, oldDic):
    length = 0
    for key in newDic:
        # print(key)
        if filemd5List in key or tempmd5List in key:
            continue
        if ignore_dir in key:
            continue

        newMd5 = newDic[key]
        oldMd5 = None
        if key in oldDic:
            oldMd5 = oldDic[key]
        if newMd5 != oldMd5:
            # if length == 0:
            #     # 没有就创建
            #     if not os.path.exists(newres_dir):
            #         os.makedirs(newres_dir)
            #     # 删除文件夹
            #     FileUtil.removeDirs(newres_dir)

            # 新增 删除 更新???
            f_src = fileutils.separator(res_dir + key)
            f_dst = fileutils.separator(newres_dir + key)
            fileutils.copyfile(f_src, f_dst) 

            print("cp res[%s] md5[%s]" % (f_dst, newMd5))

            length = length + 1           
            pass
    return length

if __name__ == '__main__':
    gen_md5(res_dir)
    pass